package com.chaoli.reggie_diy.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chaoli.reggie_diy.common.CustomException;
import com.chaoli.reggie_diy.domain.Category;
import com.chaoli.reggie_diy.domain.Dish;
import com.chaoli.reggie_diy.domain.Setmeal;
import com.chaoli.reggie_diy.mapper.CategoryMapper;
import com.chaoli.reggie_diy.service.CategoryService;
import com.chaoli.reggie_diy.service.DishService;
import com.chaoli.reggie_diy.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {

    @Autowired
    private DishService dishService;

    @Autowired
    private SetmealService setmealService;

    /**
     * 根据id进行删除分类，删除前需要判断是否关联了菜品或者套餐
     * @param id
     * @return
     */
    @Override
    public void deleteUseId(Long id) {
        //判断该id是否关联了菜品或者套餐，如果关联了就抛出业务异常
        LambdaQueryWrapper<Dish> dishQueryWrapper = new LambdaQueryWrapper<>();
        LambdaQueryWrapper<Setmeal> setmealQueryWrapper = new LambdaQueryWrapper<>();
        dishQueryWrapper.eq(Dish::getCategoryId, id);
        long dishCount = dishService.count(dishQueryWrapper);
        setmealQueryWrapper.eq(Setmeal::getCategoryId, id);
        long setmealCount = setmealService.count(setmealQueryWrapper);
        if (dishCount + setmealCount > 0){
            //关联了菜品或者套餐
            throw new CustomException("该分类关联了菜品或者套餐，无法删除");
        }

        //正常删除分类
        super.removeById(id);


    }
}
